<?php

namespace Plugins\AdminBasic\Http\Admin\Service;

use App\Models\Model;
use App\Util\Helper;
use Plugins\AdminBasic\Enums\BasicSuperConfigEnumType;
use Psr\SimpleCache\InvalidArgumentException;
use Sc\Util\ImitateAopProxy\AopProxyTrait;
use App\Exception\ApiMessageException;
use App\Http\Admin\Service\Traits\DestroyServiceTrait;
use App\Http\Admin\Service\Traits\StoreServiceTrait;
use App\Http\Admin\Service\Traits\SwitchServiceTrait;
use App\Http\Admin\Service\Traits\UpdateServiceTrait;
use App\Util\EasySearch;
use Plugins\AdminBasic\Models\BasicSuperConfig;


/**
 * 超级配置
 */
class SuperConfigService
{

    use AopProxyTrait;
    use StoreServiceTrait;
    use UpdateServiceTrait;
    use DestroyServiceTrait;
    use SwitchServiceTrait;

    public static function supportForm(): array
    {
        return [
            ['label' => '文本', 'value' => 'text'],
            ['label' => '日期时间', 'value' => 'datetime'],
            ['label' => '图片', 'value' => 'image'],
            ['label' => '图片（多）', 'value' => 'images'],
            ['label' => '开关', 'value' => 'switch'],
            ['label' => '单选', 'value' => 'radio'],
            ['label' => '多选', 'value' => 'checkbox'],
            ['label' => '下拉', 'value' => 'select'],
            ['label' => '下拉（多）', 'value' => 'selects'],
            ['label' => '文本域', 'value' => 'textarea'],
            ['label' => '富文本', 'value' => 'editor'],
            ['label' => '上传', 'value' => 'upload'],
            ['label' => '上传（多）', 'value' => 'uploads'],
        ];
    }

    public function getModel(int $id = null): ?Model
    {
        return $id ? BasicSuperConfig::find($id) : new BasicSuperConfig();
    }

    /**
     * @return array
     */
    public function lists(): array
    {
        $query = BasicSuperConfig::select(["id","sign","name","type","create_time"]);

        return EasySearch::create($query)->getData();
    }


    public function beforeDestroy(array $ids)
    {
        if (!Helper::isDev()) {
            throw new ApiMessageException("开发模式下才可操作");
        }
    }

    public function beforeUpdate(array $data)
    {
        if (!Helper::isDev()) {
            throw new ApiMessageException("开发模式下才可操作");
        }
    }

    /**
     * 保存配置信息
     *
     * @param array $data
     *
     * @return void
     * @throws ApiMessageException
     */
    public function saveBase(array $data): void
    {
        if (empty($data['id'])) {
            throw new ApiMessageException("无法保存");
        }

        $superConfig = BasicSuperConfig::find($data['id']);

        unset($data['id']);

        if ($superConfig->type === BasicSuperConfigEnumType::AdvancedArray) {
            $superConfig->config_value = $superConfig->config_value ?: [];
            if (empty($data['cid'])) {
                $data['cid'] = $superConfig->config_value ? max(array_column($superConfig->config_value, 'cid')) + 1 : 1;
                $superConfig->config_value = [...$superConfig->config_value, $data];
            }else{
                $superConfig->config_value = array_map(function ($value) use ($data){
                    return $value['cid'] === $data['cid'] ? $data : $value;
                }, $superConfig->config_value);
            }
        }else{
            $superConfig->config_value = $data;
        }
        $superConfig->save();
    }

    /**
     * @param int   $id
     * @param array $deleteIds
     *
     * @return void
     * @throws ApiMessageException
     */
    public function advancedArrayDataDestroy(int $id, array $deleteIds): void
    {
        $superConfig = BasicSuperConfig::find($id);
        if (!$superConfig) {
            throw new ApiMessageException('信息错误');
        }

        $newData = array_filter($superConfig->config_value, function ($value) use ($deleteIds){
            return !in_array($value['cid'], $deleteIds);
        });

        $superConfig->config_value = array_values($newData);
        $superConfig->save();
    }

    /**
     * @param int $page
     * @param int $limit
     *
     * @return array
     * @throws InvalidArgumentException
     */
    public function advancedArrayData(int $page, int $limit): array
    {
        /** @var BasicSuperConfig $superConfig */
        $superConfig = $this->getModel(EasySearch::query('id'));
        $allData = Helper::getSuperConfig($superConfig->sign, latest: true);

        foreach ($allData as &$datum) {
            $datum = $this->selectDataHandle($datum);
        }
        unset($datum);

        if ($search = Helper::request()->query('search')) {
            $searchValue = array_filter(empty($search['search']) ? [] : $search['search']);
            foreach ($searchValue as $field => $sv) {
                $allData = array_filter($allData, fn($value) => str_contains($value[$field] ?? "", $sv));
            }
        }

        $data = array_slice($allData, ($page - 1) * $limit, $limit);

        return [
            'data'  => $data,
            'total' => count($allData),
        ];
    }

    /**
     * @param mixed $datum
     * @return array
     */
    private function selectDataHandle(mixed $datum): array
    {
        $newData = [];
        foreach ($datum as $field => $item) {
            $newData[$field] = $item;
            if (is_array($item)) {
                if (count($item) == count($item, COUNT_RECURSIVE) && isset($item['value']) && isset($item['label'])) {
                    $newData[$field]         = $item['value'];
                    $newData["{$field}_des"] = $item['label'];
                } else if (isset($item[0]['label']) && isset($item[0]['value'])) {
                    $newData[$field]         = array_column($item, 'value');
                    $newData["{$field}_des"] = implode(',', array_column($item, 'label'));
                }
            }
        }
        return $newData;
    }
}